#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <vector>
#include <queue>

using namespace std;
using LL = long long;
const int N = 10;

struct Node
{
    string name;  //名称
    int idx;      //指向自身下标的指针
    int time;     //指向下一个下标的指针，当time=-1时，即代表当前块已经退出
    int run_time; //要求运行时间
    int priority; //优先数
    bool state;   //状态

    bool operator< (const Node& w) const {
        return this->priority < w.priority;
    }

}node[5];
priority_queue<Node> q;     //实现动态排序的堆
int que[N];    //手写的队列


/*
打印PCB块中的数据的函数
*/
void print_all() {
    for (int i = 0; i < 5; i++) {
        cout << "第" << i << "个PCB块.  进程名" << node[i].name << ",时间: " << node[i].time << ",要求运行时间: " << node[i].run_time << ",优先数： " << node[i].priority << ",状态：" << node[i].state << '\n';
    }
}

/**
 * 维护PCB块中time指针
 * 
 */
void maintenancePointer() {
    int hh = 0, tt = -1;
    while (!q.empty()) {
        Node temp = q.top();
        que[++tt] = temp.idx;
        q.pop();
    }

    for (int i = 0; i + 1 <= tt; i++) {
        node[que[i]].time = node[que[i + 1]].idx;
        q.push(node[que[i]]);
    }

    node[que[tt]].time = -1;
    q.push(node[que[tt]]);

}

void solve() {

    node[0] = { "p1", 0, 3, 2, 1, true };
    node[1] = { "p2", 1, 3, 3, 5, true };
    node[2] = { "p3", 2, 3, 1, 3, true };
    node[3] = { "p4", 3, 3, 2, 4, true };
    node[4] = { "p5", 4, 3, 4, 2, true };

    q.push(node[0]);
    q.push(node[1]);
    q.push(node[2]);
    q.push(node[3]);
    q.push(node[4]);
    maintenancePointer();
    cout << "程序的运行初值" << '\n';
    print_all();

    int T = 1;
    while (!q.empty()) {
        int id = q.top().idx;
        cout << "-----------------------------------------------" << '\n';
        cout << "第" << T << "次运行: " << node[id].idx << '\n';
        
        node[id].priority -= 1;
        node[id].run_time -= 1;
        q.pop();
        if (node[id].run_time != 0) {
            q.push(node[id]);
            maintenancePointer();
        }
        else {
            node[id].time = -1;
            node[id].state = false;
        }
        cout << "当前所有PCB块的状态" << '\n';
        print_all();
        T++;
    }

}

int main() {
    freopen("out.txt", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();


    return 0;
}